package com.app.studyroom;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.studyroom.adapter.ApprovalTaskAdapter;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.ssrGet.ApprovalTaskResponse;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AdminApprovalTaskActivity extends BaseActivity {

    private RecyclerView recyclerView;
    private ApprovalTaskAdapter adapter;
    private TextView tvPageIndicator;
    private Button btnPrevPage, btnNextPage;

    private List<ApprovalTaskResponse> taskList = new ArrayList<>();
    private int currentPage = 1;
    private final int pageSize = 11;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_center);

        recyclerView = findViewById(R.id.approval_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ApprovalTaskAdapter(this, taskList, this::refreshList);
        recyclerView.setAdapter(adapter);

        tvPageIndicator = findViewById(R.id.tvPageIndicator);
        btnPrevPage = findViewById(R.id.btnPrevPage);
        btnNextPage = findViewById(R.id.btnNextPage);

        btnPrevPage.setOnClickListener(v -> {
            if (currentPage > 1) {
                currentPage--;
                refreshList();
            }
        });

        btnNextPage.setOnClickListener(v -> {
            currentPage++;
            refreshList();
        });

        findViewById(R.id.ic_back).setOnClickListener(v -> finish());

        refreshList();
    }

    private void refreshList() {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", "");

        Log.d("接口调用", "准备请求任务列表，token = " + token);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getApprovalTaskList(token).enqueue(new Callback<List<ApprovalTaskResponse>>() {
            @Override
            public void onResponse(Call<List<ApprovalTaskResponse>> call, Response<List<ApprovalTaskResponse>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    List<ApprovalTaskResponse> allTasks = response.body();

                    Log.d("任务数量", "共返回任务数：" + allTasks.size());

                    int total = allTasks.size();
                    int fromIndex = (currentPage - 1) * pageSize;
                    int toIndex = Math.min(fromIndex + pageSize, total);

                    if (fromIndex >= total) {
                        currentPage = 1;
                        fromIndex = 0;
                        toIndex = Math.min(pageSize, total);
                    }

                    taskList = allTasks.subList(fromIndex, toIndex);
                    adapter.updateTaskList(taskList);
                    tvPageIndicator.setText("第 " + currentPage + " 页");

                    // 翻页按钮状态控制
                    boolean isFirstPage = currentPage == 1;
                    boolean isLastPage = currentPage * pageSize >= total;

                    btnPrevPage.setEnabled(!isFirstPage);
                    btnNextPage.setEnabled(!isLastPage);

                    btnPrevPage.setAlpha(!isFirstPage ? 1.0f : 0.4f);
                    btnNextPage.setAlpha(!isLastPage ? 1.0f : 0.4f);

                } else {
                    Log.e("响应失败", "状态码：" + response.code());
                    showToast("数据加载失败");
                }
            }

            @Override
            public void onFailure(Call<List<ApprovalTaskResponse>> call, Throwable t) {
                Log.e("任务接口失败", "请求失败", t);
                showToast("请求失败：" + t.getMessage());
            }
        });
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}
